<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :max-length="255" :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入流程名称"></a-input>

                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep :multi="false" v-model="model.proposer" disabled></select-user-by-dep>
                  <!-- :disabled=formDisabled -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart v-model="model.proposerDeptId" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <a-input v-model="model.createTime" placeholder="请输入申请时间" disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productTeam">
                  <select-team-input :disabled="formDisabled" v-model="model.productTeam" :tdlx="3"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="报销金额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reimbursementAmount">
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    v-model="model.reimbursementAmount"
                    placeholder="请输入报销金额"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="绩效信息">
            <erp-achievements-extraction-dt-list ref="detailList" @calculateTotalAmount="calculateTotalAmount" :disabled="formDisabled"/>
          </a-collapse-panel>

          <!-- 附件信息 -->
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="attachments">
                  <j-upload :disabled="formDisabled" v-model="model.attachments"></j-upload>
                  <!-- <a-button v-else icon="download" @click="viewFile(model.attachments)">文件列表</a-button> -->
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <!-- <a-row :gutter="48">
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row> -->

      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
    </j-form-container>

    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpAchievementsExtractionFormPrint v-if="formBpm" class="print_style" id="achievementsExtraction" :formData="model" :formDataHistory="formData"></ErpAchievementsExtractionFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue, viewFile } from '@/utils/util'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'

  import ViewFileModal from '@/views/scy/components/ViewFileModal';
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import moment from 'moment'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import { mapGetters } from 'vuex'
  import ErpAchievementsExtractionDtList from '../ErpAchievementsExtractionDtList.vue';
  import Print from '@/utils/print/printarea.js';

  import { Decimal } from 'decimal.js'
  import ErpAchievementsExtractionFormPrint from './ErpAchievementsExtractionFormPrint' // 打印
  export default {
    name: 'ErpAchievementsExtractionForm',
    mixins: [viewFile],
    components: {
      ErpAchievementsExtractionDtList,
      ViewFileModal,
      SelectUserByDep,
      SelectTeamInput,
      SelectCompanyInput,
      SelectCustomerInput,
      ErpAchievementsExtractionFormPrint,
      CommonFlowList
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model: {
         },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          proposer: [
            { required: true, message: '请输入申请人!' }
          ],
          proposerDeptId: [
            { required: true, message: '请输入申请部门!' }
          ],
          bpmBizTitle: [
            { required: true, message: '请输入流程标题!' }
          ],
          createTime: [
            { required: true, message: '请输入申请日期!' }
          ],
          productTeam: [
            { required: true, message: '请选择生产团队!' }
          ],
          reimbursementAmount: [
            { required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入报销金额!' }
          ]
        },
        url: {
          add: '/api/erp/omc/task/achievementsextraction/erpAchievementsExtraction/add',
          edit: '/api/erp/omc/task/achievementsextraction/erpAchievementsExtraction/edit',
          queryById: '/api/erp/omc/task/achievementsextraction/erpAchievementsExtraction/queryById',
          getBillNo: '/api/erp/omc/task/achievementsextraction/erpAchievementsExtraction/getBillNo'
        },
        activeKey: ['1', '2', '3'],
        dictOptions: {}
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));

      // 加载数据字典信息
      this.initDictConfig();
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),

      // 获取编号
      getBillNo() {
        let that = this;
        getAction(this.url.getBillNo, {}).then((res) => {
          if (res.success) {
            let data = res.result.records || res.result
            this.$set(this.model, 'billNo', data);
            // this.$set(this.model, 'bpmBizTitle', this.userInfo().employee.name+'-'+data);
          }
        })
      },

      initDictConfig() {
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamId', res.result)
          }
        })
      },

      // 子表保存触发回调
      calculateTotalAmount(data) {
        // 计算子表总金额
        if (data && data.length > 0) {
          // this.model.reimbursementAmount = data.reduce((pre, cur) => {return pre + cur.achievementsMoney;},0);
          let temp = data.reduce(function(prev, cur) {
            // return cur.achievementsMoney + prev;
            return new Decimal(cur.achievementsMoney).add(new Decimal(prev));
          }, new Decimal(0));
          this.$set(this.model, 'reimbursementAmount', temp.toNumber());
        } else {
          this.$set(this.model, 'reimbursementAmount', null);
        }
      },

      add () {
        this.edit(this.modelDefault);
        this.getBillNo();
        this.model.proposer = this.userInfo().empId;
        this.model.proposerDeptId = this.userInfo().deptId;
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        if (this.model.id) {
          this.$refs.detailList.loadData(1, this.model.id)
        } else {
          this.$refs.detailList.dataSource = []
        }
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },

      submitForm(type) {
        const that = this;
        var teamName = filterMultiDictText(this.dictOptions['teamId'], this.model.productTeam + '')
        this.$set(this.model, 'bpmBizTitle', (this.model.productTeam ? teamName + ' - ' : '') + this.userInfo().employee.name + '-' + moment(this.model.createTime).format('YYYY-MM-DD') + (this.model.reimbursementAmount ? ' - ' + this.model.reimbursementAmount :''));
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          // 触发表单验证
          let details = this.$refs.detailList.submitForm()
          if (!details.length > 0) {
            this.$message.warning('请添加绩效信息！');
            this.$emit('unButtonDisable');
            return
          }
          if (!this.model.createTime || !this.model.proposer || !this.model.proposerDeptId) {
            this.$message.warning('请确保申请时间、申请人、申请部门字段值存在，如不存在请尝试刷新缓存！');
            this.$emit('unButtonDisable');
            return
          }
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        this.model.erpAchievementsExtractionDts = this.$refs.detailList.submitForm() || []
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#achievementsExtraction',
          popTitle: '绩效提取单详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
